﻿using MvcPaging;
using Ninject;
using Peninsula.DataAccess.POCO;
using Peninsula.Site.Data.Constant;
using Peninsula.Site.Data.Models;
using Peninsula.Site.Data.Result;
using Peninsula.Utility.Extensions;
using Peninsula.Utility.Helper;
using Peninsula.Web.Areas.Backstage.Models.RepairOrder;
using Peninsula.Web.Areas.Backstage.Models.StoreManger;
using Peninsula.Web.Infrastructure;
using SMS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web.Mvc;

namespace Peninsula.Web.Areas.Backstage.Controllers
{
    public class StoreMangerController : AdminBaseController
    {
        TotalList list = new TotalList();


        string[] CateporyMonth = new string[] { "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" };

        [Inject]
        public IServices.IStoreService StoreService { get; set; }
        [Inject]
        public IServices.IStoreMangerService StoreMangerService { get; set; }

        [Inject]
        public IServices.IRepairOrderService RepairOrderService { get; set; }

        [Inject]
        public IServices.IMaintenanceStaffService MaintenanceStaffService { get; set; }

        [Inject]
       public IServices.IStoreRestatisticsService StoreRestatisticsService { get; set; }

        static  string roleName = RoleEnum.StoreManger.EnumDescription();

        /// <summary>
        /// 查询店面管理员
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        // GET: Backstage/StoreManger
        public ActionResult Index(StoreMangerPagedListModel viewModel)
        {

            SetPageTitle("店面管理员");
           // SetBreadcrumb(parentName: "基本管理");
            IQueryable<Admin> query = AdminManager.AdminProvider.Entities.Where(q=>q.StoreMangerId!=null);
            if (viewModel.Keyword.IsNotNullAndNotWhiteSpace())
            {
                query = query.Where(q => q.UserName.Contains(viewModel.Keyword) ||
                q.TrueName.Contains(viewModel.Keyword) || q.Phone.Contains(viewModel.Keyword));

            }
            viewModel.PagedList = query.OrderByDescending(s => s.CreatedTime).ToPagedList(viewModel.PageIndex, viewModel.Size);
            viewModel.QueryParameter = GetParameterFromQueryString();
            return View(viewModel);
        }

        /// <summary>
        /// 编辑或新增店面管理员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateOrEditStoreManger(string id)
        {
            Peninsula.DataAccess.POCO.Admin admin = null;

            if (id.IsNotNullAndNotWhiteSpace())
            {
                admin = AdminManager.Get(a => a.Id == id);
                admin.StoreManger.Stores = StoreService.Entities.Select(
                   s => new SelectListItem()
                   {
                       Value = s.Id,
                       Text = s.Name
                   }).ToList();
                if (admin.IsNull())
                {
                    return RedirectToError("没有找到对应的店面管理员", code: 404);
                }
                ViewBag.IsEdit = true;
            }
            else
            {
                admin = new Peninsula.DataAccess.POCO.Admin();
                admin.StoreManger = new StoreManger();
                admin.StoreManger.Stores = StoreService.Entities.Select(
                    s => new SelectListItem()
                    {
                        Value = s.Id,
                        Text=s.Name
                    }).ToList();
                ViewBag.IsEdit = false;
            }

            
            ViewBag.AllRoles = RoleManager.RoleProvider.Entities.Where(r=>r.RoleName==roleName);
          
            string PageTitle = ViewBag.IsEdit ? "编辑店面管理员" : "创建店面管理员";
            SetPageTitle(PageTitle);
            //SetBreadcrumb(parentName: "账户管理");
            SetBreadcrumb(currentName:PageTitle, parentName: "维修人员", parentUrl: Url.Action("Index", "StoreManger"));
            return View(admin);
        }

        /// <summary>
        /// 编辑或新增店面管理员
        /// </summary>
        /// <param name="isEdit"></param>
        /// <param name="postAdmin"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrEditStoreManger(bool isEdit, Peninsula.DataAccess.POCO.Admin postAdmin, string[] role)
        {
            var result = new JsonResultData();

            result.RunWithTry(item =>
            {
                postAdmin.IsSuperAdmin = false;
                postAdmin.IsLockedOut = false;
                // StoreMangerService.Insert(storeManger);
              
                if (isEdit)
                {
                    ModelState.Remove("Password");
                }
                if (ModelState.IsValid)
                {
                    role = role ?? new string[0];
                    var face = SaveFile("FaceImg", FileSaveRule.AdminFaceSavePath);
                    if (isEdit)
                    {
                        var adminEntity = AdminManager.Get(a => a.Id == postAdmin.Id);
                        adminEntity.FaceImgPath = face ?? adminEntity.FaceImgPath;
                        adminEntity.StoreManger.StoreId= postAdmin.StoreManger.StoreId;
                        StoreMangerService.Update(adminEntity.StoreManger);
                        postAdmin.StoreMangerId = adminEntity.StoreMangerId;
                        ValueCopyHelper.CopyProperty(adminEntity, postAdmin, false,
                            nameof(postAdmin.TrueName),
                            nameof(postAdmin.Email),
                            nameof(postAdmin.Phone),
                            nameof(postAdmin.StoreMangerId),
                            nameof(postAdmin.IsSuperAdmin),
                            nameof(postAdmin.IsLockedOut));


                        adminEntity.SetUpdateInfo(AdminSession.AdminEntity.UserName);

                        //删除旧的角色
                        adminEntity.Roles.Where(r => !role.Contains(r.Id)).ToList().ForEach(r => adminEntity.Roles.Remove(r));
                        //添加新角色
                        RoleManager.All().Where(r => role.Contains(r.Id))
                            .ForEach(r => adminEntity.Roles.Add(r));

                        AdminManager.Update(adminEntity);
                        result.Success = true;
                        result.RedirectUrl = Url.Action("Index");
                        result.AddMessage("保存成功！");
                    }
                    else
                    {
                        Admin adminS = AdminManager.AdminProvider.Get(s => s.UserName == postAdmin.UserName);
                        if (adminS.IsNull())
                        {
                            StoreManger storeManger = new StoreManger();
                            storeManger.StoreId = postAdmin.StoreManger.StoreId;
                            postAdmin.StoreMangerId = storeManger.Id;
                            postAdmin.FaceImgPath = face;
                            RoleManager.All().Where(r => role.Contains(r.Id))
                                .ForEach(r => postAdmin.Roles.Add(r));

                            postAdmin.SetCreateAndUpdateInfo(AdminSession.AdminEntity.UserName);

                            AdminManager.Add(postAdmin);

                            result.Success = true;
                            result.RedirectUrl = Url.Action("Index");
                            result.AddMessage("保存成功！");
                        }
                        else
                        {
                            result.Success = false;
                            result.AddMessage("用户名存在！");
                            return;
                        }
                        
                    }

                   
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });

            return Json(result);
        }
       /// <summary>
       /// 删除店面管理员
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
        public ActionResult Delete(string id)
        {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(c =>
            {
               string StoreMangerId = AdminManager.GetById(id).StoreMangerId;
               var  isDelete = AdminManager.Delete(a => a.Id == id);
                if (!isDelete)
                {
                    c.AddMessage("删除失败");
                }
                isDelete = StoreMangerService.Delete(StoreMangerId) > 0;
                c.Success = isDelete;
                c.AddMessage("删除" + (isDelete ? "成功" : "失败"));
                if (isDelete)
                {
                    c.ReloadPage = true;
                }
            });
            return Json(result);

        }

        /// <summary>
        /// 订单大厅
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public ActionResult RepairOrderDetails(Web.Models.RepairOrder.RepairOrderPagedListModel viewModel) {
            SetBreadcrumb(currentName:"订单大厅");
            SetPageTitle("订单大厅");

            IQueryable<RepairOrder> query = RepairOrderService.Entities.Where(r=>r.Status==OrderStatus.Submitted);
            if (viewModel.Keyword.IsNotNullAndNotWhiteSpace())
            {
                query = query.Where(r => r.Name.Contains(viewModel.Keyword) || r.ItemType.Name.Contains(viewModel.Keyword));
            }
            viewModel.PagedList = query.OrderByDescending(s => s.CreatedTime).ToPagedList(viewModel.PageIndex, viewModel.Size);
            viewModel.QueryParameter = GetParameterFromQueryString();

            return View(viewModel);
        }

        /// <summary>
        /// 接单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
       
        public ActionResult AcceptOrder(string id) {

            JsonResultData result = new JsonResultData();

            result.RunWithTry(order=> {

                if (ModelState.IsValid)
                {
                    RepairOrder repairOrder = RepairOrderService.GetById(id);
                    if (repairOrder.IsNull())
                    {
                        order.Success = false;
                        order.AddMessage("订单未存在！");
                    }
                    if (repairOrder.Status!=OrderStatus.Submitted)
                    {
                        order.Success = false;
                        order.AddMessage("订单已接取");
                    }
                    StoreManger storemanger = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId);
                    repairOrder.StoreId = storemanger.StoreId;
                    repairOrder.Status = OrderStatus.Received;
                    repairOrder.SetUpdateInfo(AdminSession.AdminUserName);
                    order.Success = RepairOrderService.Update(repairOrder) > 0;
                    order.AddMessage("接单" + (order.Success ? "成功" : "失败"));
                    if (order.Success)
                    {
                        order.RedirectUrl = Url.Action("RepairOrderDetails");
                    }
                }
                else
                {
                    order.AddModelValidErrorMessage(ModelState);
                }

            });
            return Json(result,JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// 订单跟踪
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public ActionResult OrderTrackingForStoreManger(Web.Models.RepairOrder.RepairOrderPagedListModel viewModel)
        {
            SetBreadcrumb(currentName: "订单跟踪");
            SetPageTitle("订单跟踪");
            string storeId = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId).StoreId;
            IQueryable<RepairOrder> query = RepairOrderService.Entities.Where(r =>r.Status==OrderStatus.Received||r.Status==OrderStatus.Sent||r.Status==OrderStatus.OnTheWay||r.Status==OrderStatus.RepairFinished);
            query = query.Where(r => r.StoreId == storeId);
            if (viewModel.Keyword.IsNotNullAndNotWhiteSpace())
            {
                query = query.Where(r => r.Name.Contains(viewModel.Keyword) || r.ItemType.Name.Contains(viewModel.Keyword));
            }
            if (viewModel.smOrderStatus.HasValue)
            {
                query = query.Where(r => r.Status.ToString()==viewModel.smOrderStatus.ToString());
            }
            viewModel.PagedList = query.OrderByDescending(s => s.UpdatedTime).ToPagedList(viewModel.PageIndex, viewModel.Size);
            viewModel.QueryParameter = GetParameterFromQueryString();

            return View(viewModel);
        }


       /// <summary>
       /// 派遣维修人员
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
        [HttpGet]
        public ActionResult RepairOrderSend(string id) {

            RepairOrder repairOrder = RepairOrderService.GetById(id);
            string storeId = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId).StoreId;
            var MaintenanceStaffs = AdminManager.AdminProvider.Entities.Where(m => m.MaintenanceStafId!=null&&m.MaintenanceStaff.StoreId==storeId);

            RepairOrderCreateOrEditModel model = new RepairOrderCreateOrEditModel()
            {
                Id=repairOrder.Id,
                Name=repairOrder.Name,
                Description=repairOrder.Description,
                MaintenanceStaffs = MaintenanceStaffs.Select(
                    m => new SelectListItem {
                        Value = m.Id,
                        Text=m.TrueName
                    }).ToList(),
                
                Appointment=repairOrder.Appointment
                

            };
            SetBreadcrumb($"订单派遣 - {repairOrder.Name}({repairOrder.ItemType.Name})", parentName: "订单跟踪", parentUrl: Url.Action("OrderTrackingForStoreManger"));
            SetPageTitle("订单派遣");
            return View(model);
        }

        /// <summary>
        /// /派遣维修人员
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RepairOrderSend(RepairOrderCreateOrEditModel post)
        {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(r=> {
                if (ModelState.IsValid)
                {
                    RepairOrder repairOrder = RepairOrderService.GetById(post.Id);
                    if (repairOrder.IsNull())
                    {
                        r.Success = false;
                        r.AddMessage("订单不存在");
                        return;
                    }
                    repairOrder.MaintenanceStaff = AdminManager.GetById(post.MaintenanceStaffId);
                    //SMSProvider smsProvider = new SMSProvider();

                    //string strContent = new
                    //{
                    //    nameM = repairOrder.MaintenanceStaff.TrueName,
                    //    address = "西溪半岛" + repairOrder.Households.BuldiingsNum.ToString() + "号楼" + repairOrder.Households.LayersNum.ToString()
                    //    + "层" + repairOrder.Households.Numbering.ToString() + "号",
                    //    nameH = repairOrder.Households.TrueName,
                    //    phone = repairOrder.Households.Phone.ToString(),
                    //    time = repairOrder.Appointment.ToLocalYYYYMMDDHHmmss()

                    //}.ToJson().ToString();
                    //string template = "395871";
                    //string SmsResult = smsProvider.send(repairOrder.MaintenanceStaff.Phone, strContent, template);
                    //if (SmsResult.Contains("100")) {
                        if (repairOrder.IsNotNull())
                    {
                        //repairOrder.Name = post.Name;
                        //repairOrder.Description = post.Description;
                        //repairOrder.Appointment = post.Appointment;
                        repairOrder.MaintenanceStaffId = post.MaintenanceStaffId;
                        repairOrder.Status = OrderStatus.Sent;
                        repairOrder.SetUpdateInfo(AdminSession.AdminUserName);
                        r.Success = RepairOrderService.Update(repairOrder) > 0;
                        if (r.Success)
                        {
                            r.AddMessage("派遣成功");
                            r.RedirectUrl = Url.Action("OrderTrackingForStoreManger");
                        }
                    }
                    else
                    {
                        r.Success = false;
                        r.AddMessage("派遣失败");
                        r.ReloadPage = true;
                    }
                   // }
                }
                else
                {
                    r.AddModelValidErrorMessage(ModelState);
                }
            });
            return Json(result);
        }

        /// <summary>
        /// QQ邮箱通知发送
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult RepairOrderSendEmail()
        {
            string id = HttpContext.Request.Form["id"];
            string MaintenanceStaffId = HttpContext.Request.Form["MaintenanceStaffId"];

            JsonResultData result = new JsonResultData();
            result.RunWithTry(c =>
            {
                

                if (ModelState.IsValid)
                {
                    RepairOrder order = RepairOrderService.GetById(id);
                    Households households = Householdsmanger.Get(h => h.Id == order.HouseholdsId);
                    StoreManger storeManger = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId);
                    if (order.IsNotNull())
                    {
                        Admin MaintenanceStaff = AdminManager.GetById(MaintenanceStaffId);
                      
                      

                        //MailAddress MessageFrom = new MailAddress("592576605@qq.com"); //发件人邮箱地址 

                        //string MessageTo = "1791419553@qq.com"; //收件人邮箱地址 
                        //string MessageSubject = "我在测试下"; //邮件主题 
                        //string MessageBody = "忍耐哈"; //邮件内容 （一般是一个网址链接，生成随机数加验证id参数，点击去网站验证。）  

                        MailAddress MessageFrom = new MailAddress(AdminSession.AdminEntity.Email);
                        string MessageToM = MaintenanceStaff.Email;
                        string MessageSubjectM = MaintenanceStaff.TrueName.ToString()+",派遣通知：订单标题--" +order.Name;
                        string MessageBodyM = "您已被派遣，请及时上平台查看，及时上门维修！ 户主地址：" + "西溪半岛" + order.Households.BuldiingsNum.ToString() + 
                                            "号楼" + order.Households.LayersNum.ToString()+ "层" + order.Households.Numbering.ToString() + "号;户主姓名："+order.Households.TrueName+";户主联系方式：" +
                                            order.Households.Phone+";预计户主在家时间："+ order.Appointment.ToLocalYYYYMMDDHHmmss()+";校验："+DateTime.Now.ToString();
                        string MessageToH = order.Households.Email;
                        string MessageSubjectH = order.Households.TrueName.ToString() + ",已派遣通知：订单标题--" + order.Name;
                        string MessageBodyH = "您的订单已被派遣，请及时上平台查看！维修人员姓名：" + MaintenanceStaff.TrueName + ";维修人员联系方式：" +
                                            MaintenanceStaff.Phone + ";预计到达户主家时间：" + order.Appointment.ToLocalYYYYMMDDHHmmss() + ";请您准时在家！！校验：" + DateTime.Now.ToString();


                        QQMailUtity mail = new QQMailUtity();
                            if (mail.SendMail(MessageFrom,storeManger.QQEmailCode, MessageToM, MessageSubjectM, MessageBodyM)&&
                                               mail.SendMail(MessageFrom,storeManger.QQEmailCode,MessageToH,MessageSubjectH,MessageBodyH))
                            {
                                order.MaintenanceStaff = MaintenanceStaff;
                                order.MaintenanceStaffId = MaintenanceStaffId;
                                order.Status = OrderStatus.Sent;
                                order.SetUpdateInfo(AdminSession.AdminUserName);
                                c.Success = RepairOrderService.Update(order) > 0;
                                c.Success = true;
                                //c.AddMessage("成功发送邮件！派遣成功！");
                                //c.RedirectUrl = Url.Action("OrderTrackingForStoreManger");
                            //Response.Write("<script type='text/javascript'>alert('发送邮件失败');</script>");
                        }
                            else
                            {
                                c.Success = false;
                                //c.AddMessage("失败发送邮件！派遣失败");
                            //Response.Write("<script type='text/javascript'>alert('发送邮件失败');</script>");
                        }
                     }
                    
                    else
                    {
                        c.Success = false;
                        c.AddMessage("没有该订单，请重试");
                    }
                            

                }
                else
                {
                    c.AddModelValidErrorMessage(ModelState);
                }
                        
                //503839870
               
            });
            return Json(result);

        }

        /// <summary>
        /// 更改授权码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ConfigQQEmailCode()
        {

            StoreMangerCreateOrEditModel model = new  StoreMangerCreateOrEditModel();
            StoreManger storeManger = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId);
            model.IsEdit = storeManger.IsNotNull();
            model.QQEmailCode = storeManger.QQEmailCode;
            SetPageTitle("编辑邮箱授权码");
            SetBreadcrumb(parentName: "配置邮箱");
            return View(model);
        }

        /// <summary>
        /// 更改授权码
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ConfigQQEmailCode(StoreMangerCreateOrEditModel post)
        {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(s => {
                if (ModelState.IsValid)
                {
                    bool isSuccess = false;
                    StoreManger storeManger = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId);
                    bool IsEdit = storeManger.IsNotNull();
                    storeManger.QQEmailCode = post.QQEmailCode;
                    storeManger.SetCreateAndUpdateInfo(AdminSession.AdminUserName);
                    isSuccess = StoreMangerService.Update(storeManger) > 0;
                    s.Success = isSuccess;
                    s.AddMessage("保存" + (s.Success ? "成功" : "失败"));
                    if (s.Success)
                    {
                        s.RedirectUrl = Url.Action("Index","Home");
                    }
                }
                else
                {
                    s.AddModelValidErrorMessage(ModelState);
                }
            });

            return Json(result);
        }


        /// <summary>
        /// 完成订单列表
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public ActionResult AlreadyPaidDetalis(Web.Models.RepairOrder.RepairOrderPagedListModel viewModel) {

            SetBreadcrumb(currentName: "完成订单");
            SetPageTitle("完成订单");
            var query1 = StoreService.Entities;
            string storeId = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId).StoreId;
            IQueryable<RepairOrder> query = RepairOrderService.Entities.Where(r => r.Status==OrderStatus.AlreadyPaid&& r.StoreId == storeId&&r.isDeleteForS==false);
            if (viewModel.Keyword.IsNotNullAndNotWhiteSpace())
            {
                query = query.Where(r => r.Name.Contains(viewModel.Keyword) || r.ItemType.Name.Contains(viewModel.Keyword));
            }
            viewModel.PagedList = query.OrderByDescending(s => s.UpdatedTime).ToPagedList(viewModel.PageIndex, viewModel.Size);
            viewModel.QueryParameter = GetParameterFromQueryString();
            return View(viewModel);
        }

        /// <summary>
        /// 逻辑删除订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeleteRepaiOrder(string id)
        {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(c =>
            {
                var order = RepairOrderService.GetById(id);
                if (order.IsNull())
                {
                    c.Success = false;
                    c.AddMessage("未有此订单");
                }
                order.isDeleteForS = true;
                order.SetUpdateInfo(AdminSession.AdminUserName);
                c.Success = RepairOrderService.Update(order)>0;
                if (c.Success)
                {
                    c.AddMessage("删除成功");
                    c.ReloadPage = true;
                }
            });
            return Json(result);

        }




        

         /// <summary>
         /// 店面统计
         /// </summary>
         /// <returns></returns>
        [HttpGet]
        public ActionResult StoreTotal()
        {
            SetBreadcrumb(currentName: "订单统计");
            SetPageTitle("订单统计");
            return View();
        }
        /// <summary>
        /// 店面统计
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public JsonResult StoreTotal(TotalYearModel post ) {

            JsonResultData data = new JsonResultData();
            var year = HttpContext.Request.Form["dateKeyWord"];
            if (year == "")
            {
                data.Success = false;
                data.AddMessage("统计年份不能为空！");
                return Json(data);
            }
            DateTime StartTotalTime = new DateTime(int.Parse(year), 1, 1);


            //添加横坐标
            foreach (var item in CateporyMonth)
            {
                list.listCatepory.Add(item);
            }

            Series number = new Series()
            {
                id = 0,
                name = "订单数量",
                type = "bar",
                data = new List<double>(),
                itemStyle = new itemStyle { normal = new normal { color = "#2EC7C9" } },
                markPoint = new markPoint { data = new List<data>() { new data { type = "max", name = "最大值" }, new data { type = "min", name = "最小值" } } },
                markLine = new markLine { data = new List<data>() { new data { type = "average", name = "平均值" } } }

            };

            Series money = new Series()
            {
                id = 1,
                name = "订单钱款",
                type = "bar",
                data = new List<double>(),
                itemStyle = new itemStyle { normal = new normal { color = "#FFBB73" } },
                markPoint = new markPoint { data = new List<data>() { new data { type = "max", name = "最大值" }, new data { type = "min", name = "最小值" } } },
                markLine = new markLine { data = new List<data>() { new data { type = "average", name = "平均值" } } }

            };


            StoreManger storemanger = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId);

            if (StartTotalTime.Year == DateTime.Now.Year)//今年
            {
                IQueryable<StoreRestatistics> query = StoreRestatisticsService.Entities;
                for (DateTime dt = StartTotalTime; dt < DateTime.Now; dt = dt.AddMonths(1))
                {
                    
                    query = query.Where(q => q.TotalDateTime.Value.Year == dt.Year && q.TotalDateTime.Value.Month == dt.Month && q.StoreId == storemanger.StoreId);
                    var storeRestatistics = query.SingleOrDefault();
                    if (query.Count() == 0)
                    {
                        number.data.Add(0);
                        money.data.Add(0);
                    }
                    else
                    {
                        number.data.Add(storeRestatistics.Number);
                        money.data.Add(storeRestatistics.TotalPrice.AsDouble());
                    }
                }


            }
            else if (StartTotalTime.Year < DateTime.Now.Year) //过去
            {
                DateTime FinishDateTime = StartTotalTime.AddYears(1);
                IQueryable<StoreRestatistics> query = StoreRestatisticsService.Entities;
                for (DateTime dt = StartTotalTime; dt < FinishDateTime; dt = dt.AddMonths(1))
                {
                    query = query.Where(q => q.TotalDateTime.Value.Year == dt.Year && q.TotalDateTime.Value.Month == dt.Month && q.StoreId == storemanger.StoreId);
                    var storeRestatistics = query.SingleOrDefault();
                    if (query.Count() == 0)
                    {
                        number.data.Add(0);
                        money.data.Add(0);
                    }
                    else
                    {
                        number.data.Add(storeRestatistics.Number);
                        money.data.Add(storeRestatistics.TotalPrice.AsDouble());
                    }

                }

            }
            else if (StartTotalTime.Year > DateTime.Now.Year)//将来
            {

            }
            else
            {

            }
            list.listLegend.Add(number.name);
            list.listLegend.Add(money.name);
            list.listSeries.Add(number);
            list.listSeries.Add(money);
            return Json(list);
        }

    }


}